import { ReloadOutlined } from '@ant-design/icons'
import { formatTime } from '@gnlab/utils'
import { Table, message, Button } from 'antd'
import services from '@/services'
import { SendMomentConfigStatus } from '@/services/features/send-moment'
import type { SendMomentConfig } from '@/services/features/send-moment'
import EditConfigModal from './edit'
import ConfigTasksModal from './tasks'
import './Content.module.less'

export default function Content() {
  const [configs, setConfigs] = useState<SendMomentConfig[]>([])
  const [loading, setLoading] = useState(false)
  const loadConfigs = useCallback(async () => {
    setLoading(true)
    const res = await services.features.sendMoment.loadConfigs()
    if (res.success) setConfigs(res.data)
    else void message.warning('获取配置列表失败')
    setLoading(false)
    return res.success
  }, [])

  const [cancelling, setCancelling] = useState(false)
  const cancel = useCallback(
    async (config: SendMomentConfig) => {
      setCancelling(true)
      const res = await services.features.sendMoment.addOrUpdateConfig({
        ...config,
        status: SendMomentConfigStatus.Cancelled,
      })
      if (res.success) void message.success('已取消发送')
      else void message.warning(`取消失败：${res.error}`)
      await loadConfigs()
      setCancelling(false)
    },
    [loadConfigs],
  )

  const [showingDetail, setShowingDetail] = useState<SendMomentConfig | null>(null)

  const [editing, setEditing] = useState<false | true | SendMomentConfig>(false) // true: 新建  SendMomentConfig: 编辑
  const finishEdit = useCallback(() => {
    setEditing(false)
    void loadConfigs()
  }, [loadConfigs])

  const blocking = loading || cancelling

  useEffect(() => {
    void loadConfigs()
    const intervalId = setInterval(async () => loadConfigs(), 15 * 1000) // 定时刷新配置列表，因为配置状态随时可能变化
    return () => clearInterval(intervalId)
  }, [loadConfigs])

  const renderStatus = useCallback((config: SendMomentConfig) => {
    if (config.status === SendMomentConfigStatus.Idle) {
      return config.sendTime !== null
        ? `将于 ${formatTime(config.sendTime * 1000)} 发送`
        : '正在发送' // 此状态为“立即发送”的任务正在等待队列定时执行发送，因为它一定是马上会发送且无法取消的，也显示为“正在发送”
    }
    if (config.status === SendMomentConfigStatus.Cancelled) return '已取消'
    if (config.status === SendMomentConfigStatus.Sending) return '正在发送'
    return '完成'
  }, [])

  const renderContacts = useCallback((config: SendMomentConfig) => {
    return config.contacts === null ? (
      <span styleName="contacts-all">全部联系人</span>
    ) : (
      config.contacts.length
    )
  }, [])

  const renderActions = useCallback(
    (config: SendMomentConfig) => {
      return <>
        <Button type="link" onClick={() => setShowingDetail(config)}>
          查看详情
        </Button>

        {config.sendTime !== null && config.status === SendMomentConfigStatus.Idle ? (
          <Button type="link" onClick={() => setEditing(config)}>
            编辑
          </Button>
        ) : null}

        {config.sendTime !== null && config.status === SendMomentConfigStatus.Idle ? (
          <Button type="link" onClick={async () => cancel(config)} danger>
            取消发送
          </Button>
        ) : null}
      </>
    },
    [cancel],
  )

  const tableRef = useRef<HTMLDivElement>(null)
  function add() {
    // 表格滚动回顶部，以便保存回来时看到最新创建出来的内容
    if (tableRef.current) tableRef.current.querySelector('.ant-table-body')?.scrollTo(0, 0)
    setEditing(true)
  }

  return <>
    <header>
      <div styleName="tips">
        发送企业朋友圈，本功能无法突破企微的每日朋友圈发送限制，请自行注意发送条数。
      </div>
      <div styleName="header-actions">
        <Button disabled={blocking} type="primary" onClick={add}>
          创建朋友圈发送任务
        </Button>
        <a onClick={loadConfigs}>
          <ReloadOutlined />
          刷新
        </a>
      </div>
    </header>

    <Table<SendMomentConfig>
      rowKey="id"
      dataSource={configs}
      scroll={{ y: 300 }}
      pagination={false}
      loading={blocking}
      ref={tableRef}
    >
      <Table.Column<SendMomentConfig> title="任务名称" width={180} dataIndex="name" />
      <Table.Column<SendMomentConfig>
        title="预计发送人数"
        width={120}
        align="center"
        render={renderContacts}
      />
      w222
      <Table.Column<SendMomentConfig> title="状态" key="status" width={160} render={renderStatus} />
      <Table.Column<SendMomentConfig>
        title="操作"
        key="actions"
        width={160}
        styleName="actions"
        render={renderActions}
      />
    </Table>

    <ConfigTasksModal config={showingDetail ?? undefined} onClose={() => setShowingDetail(null)} />
    <EditConfigModal editing={editing} onFinish={finishEdit} />
  </>
}
